package com.lovehena.service;

import com.lovehena.entity.Area;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AreaServiceImpl {
    public List<Area> getAreas() {
        List<Area> areas = initAreas();
        List<Area> tree = buildAreaTree(areas);
        return tree;
    }

    private List<Area> initAreas() {
        List<Area> areas = new ArrayList<Area>();
        // 浙江部分省市区数据
        areas.add(new Area("zhejiang", "", "浙江省", 1)); // 真实的各个省市区的行政编码可以从网上搜索获取
        areas.add(new Area("hangzhou", "zhejiang", "杭州市", 2));
        areas.add(new Area("yuhang", "hangzhou", "余杭区", 2));
        areas.add(new Area("binjiang", "hangzhou", "滨江区", 2));
        areas.add(new Area("xiaoshan", "hangzhou", "萧山区", 2));
        areas.add(new Area("gongshu", "hangzhou", "拱墅区", 2));
        // 添加三级行政区
        areas.add(new Area("cangqian", "yuhang", "仓前街道", 3));

        // 上海市部分区数据
        areas.add(new Area("shanghai", "", "上海市", 1));
        areas.add(new Area("minhang", "shanghai", "闵行区", 2));
        areas.add(new Area("songjiang", "shanghai", "松江区", 2));

        // 北京市部分区数据
        areas.add(new Area("beijing", "", "北京市", 1));
        areas.add(new Area("haidian", "beijing", "海淀区", 2));
        areas.add(new Area("chaoyang", "beijing", "朝阳区", 2));
        return areas;
    }

    private List<Area> buildAreaTree(List<Area> allAreas) {
        // 过滤一级行政组织
        List<Area> level1Areas = allAreas.stream().filter(item -> item.getLevel() == 1).collect(Collectors.toList());
        for (Area level1Area : level1Areas) {
            level1Area.setChildren(getChildren(level1Area.getCode(),allAreas));
        }
        // 构建好的组织树中 第一层是一级行政区如 浙江、上海、北京
        // 这些一级行政区下挂着二级行政区 各个二级行政区下又挂着三级行政区 以此类推
        // 故返回构建好的一级行政区即可
        return level1Areas;
    }

    /**
     * 递归获取某一行政组织的下级行政组织
     *
     * @param code 行政组织编码
     * @return
     */
    private List<Area> getChildren(String code,List<Area> allAreas) {
        List<Area> children = allAreas.stream().filter(item -> item.getParentCode().equals(code)).map(item -> {
            item.setChildren(getChildren(item.getCode(),allAreas)); // 每一个下级行政组织可能又有自己的下级行政组织 递归获取 封装后返回
            return item;
        }).collect(Collectors.toList());
        return children;
    }
}
